import React, { Component, useEffect, useState } from "react";
import { View } from "@tarojs/components";
import { Accordion } from "../../../components/Accordion";
import "./index.scss";
import { StackAvatars } from "../../../../src/components/stack-avatars";
import { SearchBar } from "../../../../src/components/search-bar";
import { CommonList } from "../../../../src/components/common-list";
import { NoRecord } from "../../../../src/components/no-record";
import { fetchRecords, updateTaskStatus } from "../../../../src/api/task-list";
import Collapsible from "react-collapsible";

import avatar from "../../../assets/avatar.png";
import NoTask from "../../../assets/no-task.png";
import { AtFloatLayout } from "taro-ui";
import classNames from "classnames";
import Taro, { getCurrentInstance } from "@tarojs/taro";
import { RootStore } from "src/store/root-store";
import { inject, observer } from "mobx-react";
import { IChildren, IGroupObj, IStateOptions, ITaskList } from "src/interfaces";
import dayjs from "dayjs";
import { textColorMap, getOssUrl } from "../../../utils";
import { debounce } from "debounce";

interface Props {
  rootStore?: RootStore;
}

interface ChildrenType {
  type: string;
  stateId: string;
  bg: string;
  childLen: number;
  title: string;
  deadline: string | number;
  recordId: string;
  stateOptions: IStateOptions[];
  originId: string;
  fieldId?: string;
  fieldType?: string;
}
// 分类：阶段(fieldType:18) 任务状态(fieldId:61ce9a6acf529c341c7ef8d1)
const StageOrStatusHeader = (groupObj: IGroupObj[], progress: string) => {
  return (
    <div className="task-header common-padding">
      <span className="iconfont icon-down-fill"></span>
      {groupObj.map((item) => {
        return (
          <div
            className="badge"
            style={{
              background: item?.color,
              color: textColorMap?.[item?.color || "#fff"],
            }}
            key={item?.name || item?.value}
          >
            {item?.name || item?.value}
          </div>
        );
      })}
      {progress && <span className="progress">{progress}</span>}
    </div>
  );
};

// 分类：单选/多选 (单选fieldType:3、多选 fieldType:4)
const SelectorHeader = (groupObj: IGroupObj[]) => {
  return (
    <div className="task-header common-padding">
      <span className="iconfont icon-down-fill"></span>
      {groupObj?.map((item) => {
        return (
          <div
            className="badge status"
            style={{
              background: item?.color || "#FFFFFF",
              color: textColorMap?.[item?.color || "#fff"],
            }}
          >
            {item?.value}
          </div>
        );
      })}
    </div>
  );
};

// 分类：人员 (fieldType:11)
const MemberHeader = (groupObj: IGroupObj[]) => {
  let imgs: any[] = [],
    noAssign = true,
    names: string[] = [];
  groupObj?.forEach((item) => {
    if (item?.value !== "无") noAssign = false;
    imgs.push({
      src:
        item?.value === "无"
          ? ""
          : getOssUrl({
              bucketName: item?.img?.bucketName || "",
              path: item?.img?.path || "",
            }),
      text: item?.value === "无" ? "无" : item?.nickName,
    });
    names.push(item?.nickName || "");
  });
  return (
    <div className="task-header common-padding">
      <span className="iconfont icon-down-fill"></span>
      {noAssign ? (
        <span className="name">未分配</span>
      ) : (
        <div
          style={{
            width: "100%",
            display: "flex",
            alignItems: "center",
          }}
        >
          <StackAvatars imgs={imgs} />
          <span className="name">{names?.join("，")}</span>
        </div>
      )}
    </div>
  );
};

// 分类：复选框 (fieldType:7)
const CheckboxHeader = (groupObj: IGroupObj[]) => {
  return (
    <div className="task-header common-padding">
      <span className="iconfont icon-down-fill"></span>
      {groupObj[0]?.id !== "false" ? (
        <div
          className="iconfont icon-Checkbox_unselect1 final-icon"
          style={{
            color: groupObj[0]?.color,
          }}
        ></div>
      ) : (
        <div
          className="iconfont icon-a-noCheckbox_unselect final-icon"
          style={{
            color: "#8A909F",
          }}
        ></div>
      )}
      {groupObj?.map((item) => {
        return <span className="title">{item?.value}</span>;
      })}
    </div>
  );
};

// 分类：确认状态 (fieldId:61ce9a6acf529c341c7ef8c6)
const ConfirmStatusHeader = (groupObj: IGroupObj[]) => {
  const statusDom = {
    已超期: (
      <div className="confirm-status">
        <span
          className="iconfont icon-yichaoqi"
          style={{ color: "#f4c55b" }}
        ></span>
        <span className="status-text">已超期</span>
      </div>
    ),
    待修改: (
      <div className="confirm-status">
        <span
          className="iconfont icon-daixiugai"
          style={{ color: "#ed5b56" }}
        ></span>
        <span className="status-text">待修改</span>
      </div>
    ),
    已确认: (
      <div className="confirm-status">
        <span
          className="iconfont icon-checkbox-circle-fill"
          style={{ color: "#82c560" }}
        ></span>
        <span className="status-text">已确认</span>
      </div>
    ),
    已撤回: (
      <div className="confirm-status">
        <span
          className="iconfont icon-yichehui"
          style={{ color: "#cfd1d7" }}
        ></span>
        <span className="status-text">已撤回</span>
      </div>
    ),
    待确认: (
      <div className="confirm-status">
        <span
          className="iconfont icon-daiqueren"
          style={{ color: "#8b909e" }}
        ></span>
        <span className="status-text">待确认</span>
      </div>
    ),
    无: (
      <span className="status-text" style={{ marginLeft: "0" }}>
        无状态
      </span>
    ),
  };
  return (
    <div className="task-header common-padding">
      <span className="iconfont icon-down-fill"></span>
      {groupObj?.map((item) => {
        return statusDom[item?.value || ""];
      })}
    </div>
  );
};

const ListItem = (
  children: IChildren[],
  spaceId: string,
  channelId: string,
  channelName: string,
  setIsOpened: Function,
  setCurId: Function,
  setStatusList: Function,
  fieldId?: string,
  fieldType?: string
) => {
  const data: ChildrenType[] = children?.map((item) => {
    let title = "",
      deadline: string | number = "",
      childLen = item?.children?.length;
    item?.data?.forEach((dataItem) => {
      if (dataItem?.fieldId === "61ce9a6acf529c341c7ef8c0") {
        title = dataItem?.value || "无";
      } else if (dataItem?.fieldId === "61ce9a6acf529c341c7ef8c8") {
        deadline = Number(dataItem?.value);
        if (deadline > 0) {
          deadline = dayjs(deadline)?.format("YYYY/MM/DD");
        } else if (deadline < 0) {
          deadline = dayjs(Math.abs(deadline))?.format("YYYY/MM/DD HH:mm");
        }
      }
    });
    return {
      type: item?.stateOptions?.length === 2 ? "single" : "multiple",
      stateId: item?.stateId,
      bg: item?.bg || "",
      childLen,
      title,
      deadline,
      recordId: item?.recordId,
      stateOptions: item?.stateOptions,
      originId: item?.originId || "",
      fieldId,
      fieldType,
    };
  });
  const iconDom = (data: ChildrenType) => {
    const clickIconFunction = () => {
      setIsOpened(true);
      const list: any = {};
      data?.stateOptions.forEach((item) => {
        if (list[item?.statusType]) {
          list[item?.statusType] = [
            ...list[item?.statusType],
            { ...item, data },
          ];
        } else {
          list[item?.statusType] = [{ ...item, data }];
        }
      });
      setStatusList(list);
      setCurId(data?.stateId);
    };
    if (data?.type === "single") {
      return data?.stateId === "2" ? (
        <span
          className="iconfont icon-checkbox-circle-fill icon-single done"
          onClick={() => {
            clickIconFunction();
          }}
        ></span>
      ) : (
        <span
          className="iconfont icon-Checkbox_unselect icon-single"
          onClick={() => {
            clickIconFunction();
          }}
        ></span>
      );
    } else {
      return (
        <span
          className="checkbox"
          style={{
            backgroundColor: data?.bg,
          }}
          onClick={() => {
            clickIconFunction();
          }}
        ></span>
      );
    }
  };
  return (
    <div>
      {data?.map((item: ChildrenType) => {
        return (
          <div
            className={classNames("common-padding list-item", {
              cover: item?.type === "single" && item?.stateId === "2",
            })}
            key={item?.title}
          >
            {iconDom(item)}
            <div
              className="right"
              onClick={() => {
                Taro.navigateTo({
                  url: `/pages/project-check-task/index?spaceId=${spaceId}&channelId=${channelId}&channelName=${channelName}&recordId=${item?.recordId}`,
                });
              }}
            >
              <div className="item-name ellipsis">{item?.title}</div>
              {(item?.deadline !== 0 || item?.childLen > 0) && (
                <div className="font-size-12 children">
                  {item?.deadline !== 0 && (
                    <div>
                      <span className="iconfont icon-a-calendar-event-lineover font-size-12"></span>
                      <span className="item-time">{item?.deadline}</span>
                    </div>
                  )}
                  {item?.childLen > 0 && (
                    <div
                      style={{
                        display: "flex",
                        alignItems: "center",
                      }}
                    >
                      {item?.deadline !== 0 && (
                        <span className="circle"> </span>
                      )}
                      <span className="iconfont icon-task-grouping font-size-12 son"></span>
                      {item?.childLen}
                    </div>
                  )}
                </div>
              )}
            </div>
          </div>
        );
      })}
    </div>
  );
};
interface Props {
  rootStore?: RootStore;
}
const Index = ({ rootStore }: Props) => {
  const { router } = getCurrentInstance();
  const { curChannelInfo, routerChange } = rootStore as RootStore;
  const [spaceId, setSpaceId] = useState<string>("");
  const [isOpened, setIsOpened] = useState(false);
  const [searchValue, setSearchValue] = useState("");
  const [curId, setCurId] = useState("");
  const [originTaskList, setOriginTaskList] = useState<
    ITaskList[] | IChildren[]
  >([]);
  const [taskList, setTaskList] = useState<ITaskList[] | IChildren[]>([]);
  const [taskDom, setTaskDom] = useState<React.ReactElement[]>();
  const [loading, setLoading] = useState(false);
  const [statusList, setStatusList] = useState({});
  const handleInput = (v: string) => {
    setSearchValue(v);
    getTaskList(v);
  };
  const getTaskList = debounce((v) => {
    const filterTask = (originTaskList as any[])?.filter((item) => {
      const findVal = item?.children?.find((childrenItem) => {
        const name = childrenItem?.data?.find((dataItem) => {
          return dataItem?.fieldId === "61ce9a6acf529c341c7ef8c0";
        });
        return name?.value?.includes(v);
      });
      return findVal ? true : false;
    });
    setTaskList(filterTask);
    setTaskDom(getTaskDom(filterTask));
  }, 300);
  const componentDom = (type, groupObj: IGroupObj[]) => {
    let dom;
    switch (type) {
      case 3:
        dom = SelectorHeader(groupObj);
        break;
      case 4:
        dom = SelectorHeader(groupObj);
        break;
      case 7:
        dom = CheckboxHeader(groupObj);
        break;
      case 11:
        dom = MemberHeader(groupObj);
        break;
      default:
        null;
    }
    return dom;
  };
  const getTaskDom = (taskList) => {
    return taskList?.map((item) => {
      if (!item?.groupObj) return "";
      if (item?.fieldId === "61ce9a6acf529c341c7ef8d4") {
        // 阶段
        const isSingle = item?.children?.[0]?.stateOptions?.length === 2;
        let progress = "";
        if (isSingle) {
          const done = item?.children?.filter((item) => {
            return item?.stateId === "2";
          });
          progress = `${done?.length}/${item?.children?.length}`;
        } else {
          progress = `${item?.done}/${item?.total}`;
        }
        return StageOrStatusHeader(item?.groupObj, progress);
      } else if (item?.fieldId === "61ce9a6acf529c341c7ef8d1") {
        // 完成状态
        return StageOrStatusHeader(item?.groupObj, "");
      } else if (item?.fieldId === "61ce9a6acf529c341c7ef8c6") {
        // 确认状态
        return ConfirmStatusHeader(item?.groupObj);
      } else {
        return componentDom(item?.fieldType, item?.groupObj);
      }
    });
  };
  const init = async () => {
    const spaceId = router?.params?.spaceId || "";
    if (!spaceId) {
      alert("没有空间id");
      return;
    }
    setSpaceId(spaceId);
    setLoading(true);
    Taro.showLoading();
    const res = await fetchRecords(spaceId, curChannelInfo?.id, {
      viewType: "LIST",
      visible: "in",
    });
    Taro.hideLoading();
    setLoading(false);
    setOriginTaskList(res.data);
    searchValue ? handleInput(searchValue) : setTaskList(res.data);
    setTaskDom(getTaskDom(res.data));
  };
  useEffect(() => {
    window.addEventListener("popstate", (event) => {
      init();
    });
    init();
  }, []);
  if (loading) return null;
  return (
    <View className="task-list">
      {originTaskList?.length > 0 ? (
        <div className="task-list-container">
          <SearchBar value={searchValue} onInput={handleInput} />
          <div className="list-container">
            {taskList?.map((item, index) => {
              return item?.groupObj
                ? taskDom?.[index] && (
                    <Collapsible
                      trigger={taskDom?.[index]}
                      open
                      transitionTime={300}
                      transitionCloseTime={300}
                    >
                      {ListItem(
                        item?.children,
                        spaceId,
                        curChannelInfo?.id,
                        curChannelInfo?.name,
                        setIsOpened,
                        setCurId,
                        setStatusList,
                        item?.fieldId,
                        item?.fieldType
                      )}
                    </Collapsible>
                    // <Accordion header={taskDom?.[index]} key={item?.id}>
                    //   {ListItem(
                    //     item?.children,
                    //     spaceId,
                    //     curChannelInfo?.id,
                    //     setIsOpened,
                    //     setCurId,
                    //     setStatusList,
                    //     item?.fieldId,
                    //     item?.fieldType
                    //   )}
                    // </Accordion>
                  )
                : ListItem(
                    [item] as IChildren[],
                    spaceId,
                    curChannelInfo?.id,
                    curChannelInfo?.name,
                    setIsOpened,
                    setCurId,
                    setStatusList
                  );
            })}
          </div>
        </div>
      ) : (
        <NoRecord img={NoTask} text="暂无任务" />
      )}
      {Object.keys(statusList)?.length > 0 && (
        <AtFloatLayout
          className="status-select-layout"
          isOpened={isOpened}
          title="状态"
          onClose={(val) => {
            setIsOpened(val as any);
          }}
        >
          {Object.keys(statusList)?.map((item, index) => {
            return (
              <div key={item}>
                {statusList[item]?.map((statusItem) => {
                  return (
                    <div
                      className={classNames("status-item", {
                        "common-active": curId === statusItem?.id,
                      })}
                      key={statusItem?.id}
                      onClick={async () => {
                        setCurId(statusItem?.id);
                        Taro.showLoading();
                        await updateTaskStatus(spaceId, curChannelInfo?.id, {
                          recordId: statusItem?.data?.recordId,
                          // fieldId: statusItem?.data?.fieldId || "",
                          // fieldType: statusItem?.data?.fieldType || "",
                          fieldId: "61ce9a6acf529c341c7ef8d1",
                          fieldType: 3,
                          value: statusItem?.id,
                        });
                        await init();
                        await setIsOpened(false);
                      }}
                    >
                      <span
                        className="status-icon"
                        style={{
                          background: statusItem?.color,
                        }}
                      ></span>
                      <span className="status-text">{statusItem?.value}</span>
                    </div>
                  );
                })}
                {index !== Object.keys(statusList)?.length - 1 && (
                  <div className="line"></div>
                )}
              </div>
            );
          })}
        </AtFloatLayout>
      )}
    </View>
  );
};
export const TaskList = observer(inject("rootStore")(Index));
